define(function (require) {


    require('./order-detail-tpl');

    var Tpl = juicer.templates['order-detail.juicer.html'];
    var logistic = require('../../c/logistic/index');

    var orderDetail = {
        detailEntry: {},
        load: false,
        init: function (bizOrderId) {
            this.bizOrderId = bizOrderId;
            if (this.load == false) {
                this.bindEvent();
            }
            this.request();
        },

        request: function () {
            var self = this;
            CRM.request({
                "type": 'POST',
                "url": CRM.API.queryOrder,
                "dataType": "json",
                "data": JSON.stringify({
                    "bizOrderId": self.bizOrderId
                }),
                "success": function (req) {
                    var entry = req.entry;
                    if (req.status) {
                        self.detailEntry = entry;
                        eval('self.detailEntry[0].attributes=' + self.detailEntry[0].attributes);
                        self.detailEntry[0].remarkUrl = CRM.getOuterUrl('/buyer/crm/php/o2o/seller/admin/order_remark.php');
                        self.shopId = entry[0].shopId;
                        self.landmarkId = entry[0].landmarkId;
                        var detail = self.detailEntry[0].attributes;
                        if (detail == null) {
                            detail = {};
                        }
                        self.detailEntry[0].showAddressUser = detail.hasOwnProperty("modifyAddressUser") ? detail.modifyAddressUser : entry[0].buyerNick;
                        self.detailEntry[0].showMobile = detail.hasOwnProperty("modifyMobile") ? detail.modifyMobile : entry[0].mobile;
                        self.detailEntry[0].showDistrict = detail.hasOwnProperty("modifyDistrict") ? detail.modifyDistrict : entry[0].community;
                        self.detailEntry[0].showAddress = detail.hasOwnProperty("modifyAddress") ? detail.modifyAddress : entry[0].addressSnapshot;
                        self.detailEntry[0].showAddressTime = detail.hasOwnProperty("modifyAddressTime") ? detail.modifyAddressTime : entry[0].gmtCreate;
                        self.detailEntry[0].cancelUser = detail.hasOwnProperty("cancelUser") ? detail.cancelUser : entry[0].cancelUser;
                        self.getUserinfo();
                        self.getLandmark();
                    } else {
                        CRM.showDialog(req.message)
                    }
                }
            });
        },
        //获取地标信息
        getLandmark: function () {
            var self = this;
            CRM.request({
                "type": 'GET',
                "url": CRM.API.landmarkInfo + "landmarkid=" + self.landmarkId,
                "dataType": "json",
                xhrFields: {
                    withCredentials: false
                },
                "success": function (req) {
                    if (req.doc) {
                        if (req.doc.address) {
                            self.detailEntry[0].landmarkName = req.doc.address + "(" + req.doc.name + ")";
                            self.detailEntry[0].district = req.doc.district;
                        }
                    } else {
                        if (req.address) {
                            self.detailEntry[0].landmarkName = req.address + "(" + req.name + ")";
                            self.detailEntry[0].district = req.district;
                        }
                    }
                    self.getShopInfo();
                }
            });
        },
        /**
         * 查询用户信息
         */
        getUserinfo: function () {
            var self = this;
            if (self.detailEntry[0].attributes && self.detailEntry[0].attributes.cancelUser) {
                CRM.request({
                    url: CRM.getOuterUrl('/member/getUserbyUserId.do?userId=' + self.detailEntry[0].attributes.cancelUser),
                    type: 'get',
                    async: false,
                    success: function (data) {
                        if (data.status && data.entry && data.entry.realName)  {
                            self.detailEntry[0].cancelUser = "  <span style='color:red'>取消人：" + data.entry.realName + "</span>";
                        } else {
                            self.detailEntry[0].cancelUser = "";
                        }
                    }
                });
            } else {
                self.detailEntry[0].cancelUser = "";
            }
        },
        //获取店铺接口信息：催单对象和催单对象的号码
        getShopInfo: function () {
            var self = this;
            CRM.request({
                "type": 'POST',
                "url": CRM.API.queryShopById,
                "dataType": "json",
                "data": JSON.stringify({
                    "id": self.shopId,
                    "operator": $.cookie('_uk')
                }),
                "success": function (req) {
                    var entry = req.entry;
                    if (req.status) {
                        self.detailEntry[0].shopContent = entry;
                        self.getAcceptUser();
                    } else {
                        CRM.showDialog(req.message)
                    }
                }
            });
        },

        /**
         * 查询接单员
         */
        getAcceptUser: function () {
            var self = this;
            if (self.detailEntry[0].attributes && self.detailEntry[0].attributes.acceptUser) {
                CRM.request({
                    url: CRM.getOuterUrl('/member/getUserbyUserId.do?userId=' + self.detailEntry[0].attributes.acceptUser),
                    type: 'get',
                    success: function (data) {
                        if (data.status) {
                            self.detailEntry[0].acceptUser = data.entry;
                            self.getRate();
                        } else {
                            self.getRate();
                        }
                    }
                });
            } else {
                self.getRate();
            }
        },
        /**
         * 获取评价信息
         */
        getRate: function () {
            var self = this;
            CRM.request({
                url: CRM.getOuterUrl("/crm/crm/member/getBizOrderRatesByBizOrderId"),
                type: 'post',
                data: JSON.stringify({
                    "bizOrderId": self.detailEntry[0].bizOrderId
                }),
                success: function (data) {
                    if (data.status) {
                        $.each(data.entry, function (index, rate) {
                            if (rate.type == 2) {
                                self.detailEntry[0].secondRate = rate;
                            } else {
                                self.detailEntry[0].mainRate = rate;
                            }
                        });
                        self.build();
                    } else {
                        self.build();
                    }
                }
            });
        },
        /**
         * 催单操作
         */
        remindOrder: function () {
            var self = this;
            CRM.request({
                "type": 'POST',
                "url": CRM.API.remindMarkOrder,
                "dataType": "json",
                "data": JSON.stringify({
                    "bizOrderId": self.bizOrderId
                }),
                "success": function (req) {
                    if (req.status) {
                        CRM.showDialog(req.message);
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 更新评价处理结果
         * @param bizOrderId
         */
        updateRate: function (bizOrderId) {
            var self = this;
            var dataString, _data = {};
            $($("#rate_form").serializeArray()).each(function () {
                _data[this.name] = this.value;
            });
            _data.bizOrderId = bizOrderId;
            dataString = JSON.stringify(_data);
            CRM.request({
                "type": 'POST',
                "url": "../../crm/member/updateRate",
                "dataType": "json",
                "data": dataString,
                "success": function (req) {
                    if (req.status) {
                        CRM.showDialog(req.message);
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 获取预售可修改时间
         * @param itemId
         */
        getPreSalesTime: function (itemId) {
            var self = this;

            var preTpl = '<span>请选择修改时间：</span>' +
                '<select id="J_PreDay">' +
                '{@each dayList as item}' +
                '<option value="${item}">${item}</option>' +
                '{@/each}' +
                '</select>' +
                '<select id="J_PreHour">' +
                '{@each timeScopeList as item}' +
                '<option value="${item.scopestart}-${item.scopeend}">${item.scopestart} -- ${item.scopeend}</option>' +
                '{@/each}' +
                '</select>' +
                '<span>' +
                '<button type="button" id="savePreTime" class="btn btn-primary">保存</button>' +
                '</span>';

            CRM.request({
                "type": 'GET',
                "url": CRM.API.iteminfo,
                "dataType": "jsonp",
                "data": {
                    "itemId": itemId
                },
                "success": function (req) {
                    if (req.status) {
                        var contentData = req.entry.item;
                        var html = juicer(preTpl, {
                            dayList: contentData.dayList,
                            timeScopeList: contentData.timeScopeList
                        });
                        $(".J_PreDate").html(html);
                        $('#updatePreTime').hide();
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },

        /**
         * 修改预售时间
         * @param data
         * @param cb
         */
        updatePreSaleSendTime: function (data, cb) {
            var self = this;
            CRM.request({
                "type": 'POST',
                "url": CRM.API.updatePreSaleSendTime,
                "dataType": "json",
                "data": data,
                "success": function (req) {
                    if (req.status) {
                        CRM.showDialog(req.message);
                        cb && cb();
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 查询物流信息
         * @param logisticId 物流编号
         * @param companyCode 物流公司编码
         */
        queryLogistics: function (logisticId, companyCode) {
            $('[id^="pre_a_"]').popover('destroy');
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl("/trade/order/queryLogistics"),
                "dataType": "json",
                contentType: "application/x-www-form-urlencoded",
                "data": {
                    "logisticsId": logisticId,
                    "companyCode": companyCode
                },
                "success": function (req) {
                    if (req.responseCode && req.status) {
                        var contentHTML = "";
                        $.each(req.entry, function (index, item) {

                            contentHTML += "<div style='line-height: 40px;'><span class='col-sm-4'>" + CRM.formatDate(new Date(item.time)) + "</span><span class='col-sm-8'>" + item.desc + "</span></div>";
                        });
                        var templateHTML = '<div class="popover" style="max-width: 800px;width: 600px;" role="tooltip"><div class="arrow"></div><a href=javascript:$("#pre_a_' + logisticId + '").popover("destroy") title="关闭" class="close" style="padding-right: 5px;">×</a><h3 class="popover-title"></h3><div class="popover-content"></div></div>';
                        $('#pre_a_' + logisticId).popover({
                            animation: true,
                            html: true,
                            template: templateHTML,
                            placement: "bottom",
                            title: "物流详细信息",
                            content: contentHTML
                        });
                        $('#pre_a_' + logisticId).popover('show');
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 打开修改物流的编辑框
         */
        openLogisticModify: function () {
            var ids = [];
            $("input[id^='checkbox_']:checked").each(function (index, obj) {
                ids.push($(obj).val())
            })
            if (ids.length > 0) {
                var _logisticData = {};
                _logisticData.buyerNick = $("#checkbox_" + ids[0]).attr("data-buyernick");
                _logisticData.buyerMobile = $("#checkbox_" + ids[0]).attr("data-buyermobile");
                _logisticData.districtName = $("#checkbox_" + ids[0]).attr("data-districtname");
                _logisticData.buyerAddress = $("#checkbox_" + ids[0]).attr("data-buyeraddress");
                _logisticData.bizOrderId = $("#checkbox_" + ids[0]).attr("data-bizorderid");
                _logisticData.buyerCityCode = $("#checkbox_" + ids[0]).attr("data-buyercitycode");
                logistic.init(ids, _logisticData);
            } else {
                CRM.showDialog("请选择你要修改的物流信息！");
            }

        },
        bindEvent: function () {
            var self = this;
            this.load = true;
            //催单
            $(document).on('click', '#remindOrder', function () {
                var mobile = $(this).attr('data-mobile');
                if (confirm('确认拨打' + mobile)) {
                    self.remindOrder();
                }
            });
            //获取预售时间
            $(document).on('click', '#updatePreTime', function () {
                self.getPreSalesTime($(this).attr('data-id'));
            });
            //修改预售时间
            $(document).on('click', '#savePreTime', function () {
                var preDay = $('#J_PreDay'),
                    preHour = $('#J_PreHour');

                var data = JSON.stringify({
                    "bizOrderId": $('.J_BizOrderId').val(),
                    "buyerId": $('.J_BuyerId').val(),
                    "preSaleSendStartTime": preDay.val() + " " + preHour.val().split('-')[0] + ":00",
                    "preSaleSendEndTime": preDay.val() + " " + preHour.val().split('-')[1] + ":00"
                });

                if (confirm('确认是否保存修改的时间')) {
                    self.updatePreSaleSendTime(data, function () {
                        $('.J_ShowPreStartTime').html(preDay.val() + " " + preHour.val().split('-')[0] + ":00");
                        $('.J_ShowPreEndTime').html(preDay.val() + " " + preHour.val().split('-')[1] + ":00")
                    });
                }
            });
            //催单
            $(document).on('click', '#save_rate', function () {
                var id = $(this).attr('data-id');
                self.updateRate(id);
            });
        },

        build: function () {
            CRM.showModal(Tpl({
                "data": this.detailEntry
            }), $('body'));
        }

    };

    window.queryLogistics = $.proxy(orderDetail.queryLogistics, orderDetail);
    window.openLogisticModify = $.proxy(orderDetail.openLogisticModify, orderDetail);
    return orderDetail

});
